{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<a href=\"https://colab.research.google.com/github/run-llama/llama_index/blob/main/docs/examples/workflow/citation_query_engine.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Build RAG with in-line citations\n",
    "\n",
    "This notebook walks through implementation of RAG with in-line citations of source nodes, using Workflows.\n",
    "\n",
    "Specifically we will implement [CitationQueryEngine](https://github.com/run-llama/llama_index/blob/main/docs/examples/query_engine/citation_query_engine.ipynb) which gives in-line citations in the response generated based on the nodes."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "!pip install -U llama-index"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import os\n",
    "\n",
    "os.environ[\"OPENAI_API_KEY\"] = \"sk-...\""
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Download Data"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "--2024-08-15 00:23:50--  https://raw.githubusercontent.com/run-llama/llama_index/main/docs/examples/data/paul_graham/paul_graham_essay.txt\n",
      "Resolving raw.githubusercontent.com (raw.githubusercontent.com)... 2606:50c0:8000::154, 2606:50c0:8001::154, 2606:50c0:8002::154, ...\n",
      "Connecting to raw.githubusercontent.com (raw.githubusercontent.com)|2606:50c0:8000::154|:443... connected.\n",
      "HTTP request sent, awaiting response... 200 OK\n",
      "Length: 75042 (73K) [text/plain]\n",
      "Saving to: ‘data/paul_graham/paul_graham_essay.txt’\n",
      "\n",
      "data/paul_graham/pa 100%[===================>]  73.28K  --.-KB/s    in 0.01s   \n",
      "\n",
      "2024-08-15 00:23:50 (5.27 MB/s) - ‘data/paul_graham/paul_graham_essay.txt’ saved [75042/75042]\n",
      "\n"
     ]
    }
   ],
   "source": [
    "!mkdir -p 'data/paul_graham/'\n",
    "!wget 'https://raw.githubusercontent.com/run-llama/llama_index/main/docs/examples/data/paul_graham/paul_graham_essay.txt' -O 'data/paul_graham/paul_graham_essay.txt'"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Since workflows are async first, this all runs fine in a notebook. If you were running in your own code, you would want to use `asyncio.run()` to start an async event loop if one isn't already running.\n",
    "\n",
    "```python\n",
    "async def main():\n",
    "    <async code>\n",
    "\n",
    "if __name__ == \"__main__\":\n",
    "    import asyncio\n",
    "    asyncio.run(main())\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Designing the Workflow\n",
    "\n",
    "CitationQueryEngine consists of some clearly defined steps\n",
    "1. Indexing data, creating an index\n",
    "2. Using that index + a query to retrieve relevant nodes\n",
    "3. Add citations to the retrieved nodes.\n",
    "4. Synthesizing a final response\n",
    "\n",
    "With this in mind, we can create events and workflow steps to follow this process!\n",
    "\n",
    "### The Workflow Events\n",
    "\n",
    "To handle these steps, we need to define a few events:\n",
    "1. An event to pass retrieved nodes to the create citations\n",
    "2. An event to pass citation nodes to the synthesizer\n",
    "\n",
    "The other steps will use the built-in `StartEvent` and `StopEvent` events."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from llama_index.core.workflow import Event\n",
    "from llama_index.core.schema import NodeWithScore\n",
    "\n",
    "\n",
    "class RetrieverEvent(Event):\n",
    "    \"\"\"Result of running retrieval\"\"\"\n",
    "\n",
    "    nodes: list[NodeWithScore]\n",
    "\n",
    "\n",
    "class CreateCitationsEvent(Event):\n",
    "    \"\"\"Add citations to the nodes.\"\"\"\n",
    "\n",
    "    nodes: list[NodeWithScore]"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Citation Prompt Templates\n",
    "\n",
    "Here we define default `CITATION_QA_TEMPLATE`, `CITATION_REFINE_TEMPLATE`, `DEFAULT_CITATION_CHUNK_SIZE` and `DEFAULT_CITATION_CHUNK_OVERLAP`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from llama_index.core.prompts import PromptTemplate\n",
    "\n",
    "CITATION_QA_TEMPLATE = PromptTemplate(\n",
    "    \"Please provide an answer based solely on the provided sources. \"\n",
    "    \"When referencing information from a source, \"\n",
    "    \"cite the appropriate source(s) using their corresponding numbers. \"\n",
    "    \"Every answer should include at least one source citation. \"\n",
    "    \"Only cite a source when you are explicitly referencing it. \"\n",
    "    \"If none of the sources are helpful, you should indicate that. \"\n",
    "    \"For example:\\n\"\n",
    "    \"Source 1:\\n\"\n",
    "    \"The sky is red in the evening and blue in the morning.\\n\"\n",
    "    \"Source 2:\\n\"\n",
    "    \"Water is wet when the sky is red.\\n\"\n",
    "    \"Query: When is water wet?\\n\"\n",
    "    \"Answer: Water will be wet when the sky is red [2], \"\n",
    "    \"which occurs in the evening [1].\\n\"\n",
    "    \"Now it's your turn. Below are several numbered sources of information:\"\n",
    "    \"\\n------\\n\"\n",
    "    \"{context_str}\"\n",
    "    \"\\n------\\n\"\n",
    "    \"Query: {query_str}\\n\"\n",
    "    \"Answer: \"\n",
    ")\n",
    "\n",
    "CITATION_REFINE_TEMPLATE = PromptTemplate(\n",
    "    \"Please provide an answer based solely on the provided sources. \"\n",
    "    \"When referencing information from a source, \"\n",
    "    \"cite the appropriate source(s) using their corresponding numbers. \"\n",
    "    \"Every answer should include at least one source citation. \"\n",
    "    \"Only cite a source when you are explicitly referencing it. \"\n",
    "    \"If none of the sources are helpful, you should indicate that. \"\n",
    "    \"For example:\\n\"\n",
    "    \"Source 1:\\n\"\n",
    "    \"The sky is red in the evening and blue in the morning.\\n\"\n",
    "    \"Source 2:\\n\"\n",
    "    \"Water is wet when the sky is red.\\n\"\n",
    "    \"Query: When is water wet?\\n\"\n",
    "    \"Answer: Water will be wet when the sky is red [2], \"\n",
    "    \"which occurs in the evening [1].\\n\"\n",
    "    \"Now it's your turn. \"\n",
    "    \"We have provided an existing answer: {existing_answer}\"\n",
    "    \"Below are several numbered sources of information. \"\n",
    "    \"Use them to refine the existing answer. \"\n",
    "    \"If the provided sources are not helpful, you will repeat the existing answer.\"\n",
    "    \"\\nBegin refining!\"\n",
    "    \"\\n------\\n\"\n",
    "    \"{context_msg}\"\n",
    "    \"\\n------\\n\"\n",
    "    \"Query: {query_str}\\n\"\n",
    "    \"Answer: \"\n",
    ")\n",
    "\n",
    "DEFAULT_CITATION_CHUNK_SIZE = 512\n",
    "DEFAULT_CITATION_CHUNK_OVERLAP = 20"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### The Workflow Itself\n",
    "\n",
    "With our events defined, we can construct our workflow and steps. \n",
    "\n",
    "Note that the workflow automatically validates itself using type annotations, so the type annotations on our steps are very helpful!"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from llama_index.core import SimpleDirectoryReader, VectorStoreIndex\n",
    "from llama_index.core.workflow import (\n",
    "    Context,\n",
    "    Workflow,\n",
    "    StartEvent,\n",
    "    StopEvent,\n",
    "    step,\n",
    ")\n",
    "\n",
    "from llama_index.llms.openai import OpenAI\n",
    "from llama_index.embeddings.openai import OpenAIEmbedding\n",
    "\n",
    "from llama_index.core.schema import (\n",
    "    MetadataMode,\n",
    "    NodeWithScore,\n",
    "    TextNode,\n",
    ")\n",
    "\n",
    "from llama_index.core.response_synthesizers import (\n",
    "    ResponseMode,\n",
    "    get_response_synthesizer,\n",
    ")\n",
    "\n",
    "from typing import Union, List\n",
    "from llama_index.core.node_parser import SentenceSplitter\n",
    "\n",
    "\n",
    "class CitationQueryEngineWorkflow(Workflow):\n",
    "    @step\n",
    "    async def retrieve(\n",
    "        self, ctx: Context, ev: StartEvent\n",
    "    ) -> Union[RetrieverEvent, None]:\n",
    "        \"Entry point for RAG, triggered by a StartEvent with `query`.\"\n",
    "        query = ev.get(\"query\")\n",
    "        if not query:\n",
    "            return None\n",
    "\n",
    "        print(f\"Query the database with: {query}\")\n",
    "\n",
    "        # store the query in the global context\n",
    "        await ctx.store.set(\"query\", query)\n",
    "\n",
    "        if ev.index is None:\n",
    "            print(\"Index is empty, load some documents before querying!\")\n",
    "            return None\n",
    "\n",
    "        retriever = ev.index.as_retriever(similarity_top_k=2)\n",
    "        nodes = retriever.retrieve(query)\n",
    "        print(f\"Retrieved {len(nodes)} nodes.\")\n",
    "        return RetrieverEvent(nodes=nodes)\n",
    "\n",
    "    @step\n",
    "    async def create_citation_nodes(\n",
    "        self, ev: RetrieverEvent\n",
    "    ) -> CreateCitationsEvent:\n",
    "        \"\"\"\n",
    "        Modify retrieved nodes to create granular sources for citations.\n",
    "\n",
    "        Takes a list of NodeWithScore objects and splits their content\n",
    "        into smaller chunks, creating new NodeWithScore objects for each chunk.\n",
    "        Each new node is labeled as a numbered source, allowing for more precise\n",
    "        citation in query results.\n",
    "\n",
    "        Args:\n",
    "            nodes (List[NodeWithScore]): A list of NodeWithScore objects to be processed.\n",
    "\n",
    "        Returns:\n",
    "            List[NodeWithScore]: A new list of NodeWithScore objects, where each object\n",
    "            represents a smaller chunk of the original nodes, labeled as a source.\n",
    "        \"\"\"\n",
    "        nodes = ev.nodes\n",
    "\n",
    "        new_nodes: List[NodeWithScore] = []\n",
    "\n",
    "        text_splitter = SentenceSplitter(\n",
    "            chunk_size=DEFAULT_CITATION_CHUNK_SIZE,\n",
    "            chunk_overlap=DEFAULT_CITATION_CHUNK_OVERLAP,\n",
    "        )\n",
    "\n",
    "        for node in nodes:\n",
    "            text_chunks = text_splitter.split_text(\n",
    "                node.node.get_content(metadata_mode=MetadataMode.NONE)\n",
    "            )\n",
    "\n",
    "            for text_chunk in text_chunks:\n",
    "                text = f\"Source {len(new_nodes)+1}:\\n{text_chunk}\\n\"\n",
    "\n",
    "                new_node = NodeWithScore(\n",
    "                    node=TextNode.parse_obj(node.node), score=node.score\n",
    "                )\n",
    "                new_node.node.text = text\n",
    "                new_nodes.append(new_node)\n",
    "        return CreateCitationsEvent(nodes=new_nodes)\n",
    "\n",
    "    @step\n",
    "    async def synthesize(\n",
    "        self, ctx: Context, ev: CreateCitationsEvent\n",
    "    ) -> StopEvent:\n",
    "        \"\"\"Return a streaming response using the retrieved nodes.\"\"\"\n",
    "        llm = OpenAI(model=\"gpt-4o-mini\")\n",
    "        query = await ctx.store.get(\"query\", default=None)\n",
    "\n",
    "        synthesizer = get_response_synthesizer(\n",
    "            llm=llm,\n",
    "            text_qa_template=CITATION_QA_TEMPLATE,\n",
    "            refine_template=CITATION_REFINE_TEMPLATE,\n",
    "            response_mode=ResponseMode.COMPACT,\n",
    "            use_async=True,\n",
    "        )\n",
    "\n",
    "        response = await synthesizer.asynthesize(query, nodes=ev.nodes)\n",
    "        return StopEvent(result=response)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "And thats it! Let's explore the workflow we wrote a bit.\n",
    "\n",
    "- We have an entry point (the step that accept `StartEvent`)\n",
    "- The workflow context is used to store the user query\n",
    "- The nodes are retrieved, citations are created, and finally a response is returned"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Create Index"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "documents = SimpleDirectoryReader(\"data/paul_graham\").load_data()\n",
    "index = VectorStoreIndex.from_documents(\n",
    "    documents=documents,\n",
    "    embed_model=OpenAIEmbedding(model_name=\"text-embedding-3-small\"),\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Run the Workflow!"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "w = CitationQueryEngineWorkflow()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Query the database with: What information do you have\n",
      "Retrieved 2 nodes.\n"
     ]
    }
   ],
   "source": [
    "# Run a query\n",
    "result = await w.run(query=\"What information do you have\", index=index)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/markdown": [
       "The provided sources contain various insights into Paul Graham's experiences and thoughts on programming, writing, and his educational journey. For instance, he reflects on his early experiences with programming on the IBM 1401, where he struggled to create meaningful programs due to the limitations of the technology at the time [2]. He also describes his transition to using microcomputers, which allowed for more interactive programming experiences [3]. Additionally, Graham shares his initial interest in philosophy during college, which he later found less engaging compared to the fields of artificial intelligence and programming [3]. Overall, the sources highlight his evolution as a writer and programmer, as well as his changing academic interests."
      ],
      "text/plain": [
       "<IPython.core.display.Markdown object>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "from IPython.display import Markdown, display\n",
    "\n",
    "display(Markdown(f\"{result}\"))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Check the citations."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Source 1:\n",
      "But after Heroku got bought we had enough money to go back to being self-funded.\n",
      "\n",
      "[15] I've never liked the term \"deal flow,\" because it implies that the number of new startups at any given time is fixed. This is not only false, but it's the purpose of YC to falsify it, by causing startups to be founded that would not otherwise have existed.\n",
      "\n",
      "[16] She reports that they were all different shapes and sizes, because there was a run on air conditioners and she had to get whatever she could, but that they were all heavier than she could carry now.\n",
      "\n",
      "[17] Another problem with HN was a bizarre edge case that occurs when you both write essays and run a forum. When you run a forum, you're assumed to see if not every conversation, at least every conversation involving you. And when you write essays, people post highly imaginative misinterpretations of them on forums. Individually these two phenomena are tedious but bearable, but the combination is disastrous. You actually have to respond to the misinterpretations, because the assumption that you're present in the conversation means that not responding to any sufficiently upvoted misinterpretation reads as a tacit admission that it's correct. But that in turn encourages more; anyone who wants to pick a fight with you senses that now is their chance.\n",
      "\n",
      "[18] The worst thing about leaving YC was not working with Jessica anymore. We'd been working on YC almost the whole time we'd known each other, and we'd neither tried nor wanted to separate it from our personal lives, so leaving was like pulling up a deeply rooted tree.\n",
      "\n",
      "[19] One way to get more precise about the concept of invented vs discovered is to talk about space aliens. Any sufficiently advanced alien civilization would certainly know about the Pythagorean theorem, for example. I believe, though with less certainty, that they would also know about the Lisp in McCarthy's 1960 paper.\n",
      "\n",
      "But if so there's no reason to suppose that this is the limit of the language that might be known to them. Presumably aliens need numbers and errors and I/O too. So it seems likely there exists at least one path out of McCarthy's Lisp along which discoveredness is preserved.\n",
      "\n",
      "\n",
      "\n",
      "Thanks to Trevor Blackwell, John Collison, Patrick Collison, Daniel Gackle, Ralph Hazell, Jessica Livingston, Robert Morris, and Harj Taggar for reading drafts of this.\n",
      "\n"
     ]
    }
   ],
   "source": [
    "print(result.source_nodes[0].node.get_text())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Source 2:\n",
      "What I Worked On\n",
      "\n",
      "February 2021\n",
      "\n",
      "Before college the two main things I worked on, outside of school, were writing and programming. I didn't write essays. I wrote what beginning writers were supposed to write then, and probably still are: short stories. My stories were awful. They had hardly any plot, just characters with strong feelings, which I imagined made them deep.\n",
      "\n",
      "The first programs I tried writing were on the IBM 1401 that our school district used for what was then called \"data processing.\" This was in 9th grade, so I was 13 or 14. The school district's 1401 happened to be in the basement of our junior high school, and my friend Rich Draves and I got permission to use it. It was like a mini Bond villain's lair down there, with all these alien-looking machines — CPU, disk drives, printer, card reader — sitting up on a raised floor under bright fluorescent lights.\n",
      "\n",
      "The language we used was an early version of Fortran. You had to type programs on punch cards, then stack them in the card reader and press a button to load the program into memory and run it. The result would ordinarily be to print something on the spectacularly loud printer.\n",
      "\n",
      "I was puzzled by the 1401. I couldn't figure out what to do with it. And in retrospect there's not much I could have done with it. The only form of input to programs was data stored on punched cards, and I didn't have any data stored on punched cards. The only other option was to do things that didn't rely on any input, like calculate approximations of pi, but I didn't know enough math to do anything interesting of that type. So I'm not surprised I can't remember any programs I wrote, because they can't have done much. My clearest memory is of the moment I learned it was possible for programs not to terminate, when one of mine didn't. On a machine without time-sharing, this was a social as well as a technical error, as the data center manager's expression made clear.\n",
      "\n",
      "With microcomputers, everything changed. Now you could have a computer sitting right in front of you, on a desk, that could respond to your keystrokes as it was running instead of just churning through a stack of punch cards and then stopping.\n",
      "\n"
     ]
    }
   ],
   "source": [
    "print(result.source_nodes[1].node.get_text())"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "llamaindex",
   "language": "python",
   "name": "llamaindex"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
